import React, { useState } from 'react';

export default ({
  children,
  ...otherprops
}: React.AllHTMLAttributes<HTMLDivElement>) => {
  const [position, setPosition] = useState({ top: 0, left: 0 });
  const [isDrag, setIsDrag] = useState(false);
  const [isDragIn, setIsDragIn] = useState(false);
  const [currentClickLayer, setCurrentClickLayer] = useState({
    // 点击位置在点内部的位置
    offsetX: 0,
    offsetY: 0,
  });
  return (
    <div
      draggable={true}
      onDragStart={() => setIsDrag(true)}
      onDragEnter={() => setIsDragIn(true)}
      onDragLeave={() => setIsDragIn(false)}
      onMouseDown={({ nativeEvent: { offsetY, offsetX } }) =>
        setCurrentClickLayer({ offsetX, offsetY })
      }
      onDragEnd={({ nativeEvent: { offsetY, offsetX } }) => {
        setIsDrag(false);
        setPosition({
          top: position.top + offsetY - currentClickLayer.offsetY,
          left: position.left + offsetX - currentClickLayer.offsetX,
        });
      }}
      style={{
        ...position,
        ...otherprops.style,
        position: 'absolute',
        opacity: isDrag ? 0.5 : isDragIn ? 0.7 : 1,
      }}
    >
      {children}
    </div>
  );
};
